package com.uroad.jilinpda.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.method.ReplacementTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.uroad.jilinpda.R;
import com.uroad.jilinpda.activity.LoginActivity;
import com.uroad.jilinpda.activity.OBUActivationStep1Activity;
import com.uroad.jilinpda.activity.SigningQRCodeActivity;
import com.uroad.jilinpda.adapter.TobeActivatedAdapter;
import com.uroad.jilinpda.common.GlobalData;
import com.uroad.jilinpda.modle.IssueMDL;
import com.uroad.jilinpda.util.SPUtils;
import com.uroad.jilinpda.webservice.QueryWS;
import com.uroad.jilinpda.widget.ChoosePlateColorDialog;
import com.uroad.jilinpda.widget.CustomScrollView;
import com.uroad.jilinpda.widget.SYSDiaLogUtils;
import com.uroad.lib.fragment.BaseFragment;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.widget.dialog.DialogHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class TobeActivatedFragment extends BaseFragment implements OnDateSetListener, View.OnClickListener {
    private View view;
    TextView tv_begin_time, tv_end_time;
    private TimePickerDialog pickerDialog;
    private Button bt_query;
    private Context context;
    private String starttime = "", endtime = "";
    private String ticketid;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private TobeActivatedAdapter adapter;
    private RecyclerView rv_issue;
    private TextView et_user_phone;
    private TextView tv_totalamount;
    private TextView tv_tips_cords;
    private int index = 1;
    private List<IssueMDL.Data> datas;
    private boolean isFinish = false;
    private LinearLayoutManager layoutManager;
    private CustomScrollView sl_issue;
    private long start = 0, end = 0;


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_issue, null);
        //        ButterKnife.bind(view);
        context=getActivity();
        init();
        initView();
        initDialog();
        return view;
    }

    private void init(){
        ticketid = (String) SPUtils.get(getActivity(), GlobalData.sp_ticketid, "");
    }
    private void initView() {
        datas = new ArrayList<>();
        tv_begin_time = view.findViewById(R.id.tv_begin_time);
        tv_end_time = view.findViewById(R.id.tv_end_time);
        bt_query = view.findViewById(R.id.bt_query);
        rv_issue = view.findViewById(R.id.rv_issue);
        et_user_phone = view.findViewById(R.id.et_user_phone);
        tv_totalamount = view.findViewById(R.id.tv_totalamount);
        sl_issue = view.findViewById(R.id.sl_issue);
        tv_tips_cords = view.findViewById(R.id.tv_tips_cords);
        tv_tips_cords.setText("以下订单为您在地推客户端发行成功的订单，但尚未激活，请尽快为以下车辆进行激活操作。如您需要取消订单，请不要进行激活操作。");
        tv_begin_time.setOnClickListener(this);
        tv_end_time.setOnClickListener(this);
        et_user_phone.setOnClickListener(this);
        bt_query.setOnClickListener(this);
        et_user_phone.setTransformationMethod(new TransInformation());

        adapter = new TobeActivatedAdapter(getActivity());
        adapter.setOnItemClickListener(new TobeActivatedAdapter.onItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!TextUtils.isEmpty(datas.get(position).getIsgm())) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isgm", datas.get(position).getIsgm().equals("0") ? false : true);
                    bundle.putString("orderno", datas.get(position).getOrderno());
                    bundle.putString("isneedpic", datas.get(position).getIsneedpic());
                    bundle.putString("vehtype", datas.get(position).getVehtype());
                    openActivity(OBUActivationStep1Activity.class, bundle);
                }
            }
        });
        layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        rv_issue.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper. VERTICAL);
        adapter.setItemCancel(new TobeActivatedAdapter.ItemCancel() {
            @Override
            public void OnCancel(String orderno) {
                SYSDiaLogUtils.showConfirmDialogType(getActivity(), "确认取消订单？" , "", "", "确认", "我再想想", new SYSDiaLogUtils.ConfirmDialogListener() {
                    @Override
                    public void onClickButton(boolean clickLeft, boolean clickRight) {
                        if (clickLeft) {

                        } else if (clickRight) {
                            doCancel(orderno);
                        }
                    }
                });
            }

            @Override
            public void OngetCode(String orderno, String plateNumber) {
                Intent intent = new Intent();
                intent.setClass(context, SigningQRCodeActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("orderno",orderno);
                bundle.putString("plateNumber",plateNumber);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        rv_issue.setAdapter(adapter);

        sl_issue.setOnScrollChangeListener(new CustomScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollToStart() {

            }

            @Override
            public void onScrollToEnd() {
                if (!isFinish)
                    getData();
            }
        });
    }

    private void initDialog() {
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        pickerDialog = new TimePickerDialog.Builder()
                .setCallBack(this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setTitleStringId("请选择时间")
                .setMinMillseconds(System.currentTimeMillis()-tenYears)
                .setMaxMillseconds(System.currentTimeMillis())
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.colorPrimary))
                .setType(Type.YEAR_MONTH_DAY)
                .build();

    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        String text = getDateToString(millseconds);
        if (pickerDialog.getTag().equals("start")){
            tv_begin_time.setText(text);
            starttime = text;
            start = millseconds;
        } else if (pickerDialog.getTag().equals("end")){
            tv_end_time.setText(text);
            endtime = text;
            end = millseconds;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        try{
            if(getUserVisibleHint()){//界面可见时
                index = 1;
                datas.clear();
                isFinish = false;
                getData();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_begin_time:
                pickerDialog.show(getActivity().getSupportFragmentManager(), "start");
                break;
            case R.id.tv_end_time:
                pickerDialog.show(getActivity().getSupportFragmentManager(), "end");
                break;
            case R.id.et_user_phone:
//                et_user_phone.setText("");
                ChoosePlateColorDialog plateColorDialog = new ChoosePlateColorDialog(getActivity(), "2","").setOnDatePickerListener(new ChoosePlateColorDialog.OnDatePickerListener() {
                    @Override
                    public void onDatePicker(String plat, int item, String workcode) {
                        et_user_phone.setText(plat);
                    }
                });
                plateColorDialog.show();
                plateColorDialog.hideColor(true);
                break;
            case R.id.bt_query:
                if (!starttime.equals("")&&endtime.equals("")){
                    showShortToast("请选择结束时间");
                    return;
                }
                if (starttime.equals("")&&!endtime.equals("")){
                    showShortToast("请选择开始时间");
                    return;
                }
                if (start > end){
                    showShortToast("开始时间不能大于结束时间");
                    return;
                }
                index = 1;
                datas.clear();
                isFinish = false;
                getData();
                break;
        }
    }

    private void doCancel(String orderno){
        DialogHelper.showLoading(getActivity(),"");
        doRequest(QueryWS.cancel, QueryWS.cancelParams(orderno), QueryWS.cancel);
    }

    private void getData(){
        DialogHelper.showLoading(getActivity(),"");
        doRequest(QueryWS.listorder, QueryWS.listorderParams(ticketid, index+"",
                "10", starttime, endtime , et_user_phone.getText().toString().toUpperCase(), "3"), QueryWS.listorder);
    }

    @Override
    public void OnHttpTaskComplete(String result, String type) {
        DialogHelper.endLoading();
        JSONObject jsonObject = JSON.parseObject(result);
        if (FastJsonUtils.GetJsonStatu1(jsonObject)) {

            if (type.equals(QueryWS.listorder)) {
                String data = FastJsonUtils.getData(jsonObject);
                IssueMDL mdl = FastJsonUtils.parseObjectJSON(data, IssueMDL.class);
                datas.addAll(mdl.getData());
                adapter.setmDatas(datas);
                index ++;
                if (mdl.getData().size() < 10){
                    isFinish = true;
                    adapter.offFooterView();// 去掉footer
                }
                else{
                    /*TextView tv = new TextView(getActivity());
                    adapter.setFooterView(tv);
                    rv_issue.addOnScrollListener(new EndLessOnScrollListener(layoutManager){
                        @Override
                        public void onLoadMore(int currentPage) {
                            if (!isFinish)
                                getData();
                        }
                    });*/
                }
                if (mdl.getTotalamount() <= 0){
//                    if (!starttime.equals("")&&!endtime.equals(""))
//                        showShortToast("该时间段暂无订单！");
//                    else
                        showShortToast("抱歉，没有查询到订单~");
                }
                tv_totalamount.setText("订单总数："+ mdl.getTotalamount());
            }else if(type.equals(QueryWS.cancel)){
                index = 1;
                datas.clear();
                isFinish = false;
                getData();
                showShortToast("取消订单成功！");
            }
        } else {
            showShortToast(FastJsonUtils.GetErrorString(jsonObject, "msg"));
            String status = jsonObject.getString("status");
            if (status.equals("02")) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }

    private String getDateToString(long time) {
        Date d = new Date(time);
//        estimatetime = format.format(d);
        return format.format(d);
    }
    public class TransInformation extends ReplacementTransformationMethod {
        /**
         * 原本输入的小写字母
         */
        @Override
        protected char[] getOriginal() {
            return new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        }

        /**
         * 替代为大写字母
         */
        @Override
        protected char[] getReplacement() {
            return new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        }
    }
}
